package com.tqjc.system.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tqjc.system.common.constant.AddTaskConstant;
import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.controller.BaseController;
import com.tqjc.system.common.entity.VO.AddTaskVO;
import com.tqjc.system.common.entity.VO.AreaInfoVO;
import com.tqjc.system.common.entity.VO.TaskInfoVO;
import com.tqjc.system.common.enums.TaskStatusEnum;
import com.tqjc.system.common.enums.TaskTypeEnum;
import com.tqjc.system.core.model.AjaxJson;
import com.tqjc.system.core.model.PageInfo;
import com.tqjc.system.core.util.DateUtils;
import com.tqjc.system.core.util.ResponseUtil;
import com.tqjc.system.system.entity.SysAddDetailTaskEntity;
import com.tqjc.system.system.entity.SysAddPrimaryTaskEntity;
import com.tqjc.system.system.entity.SysAreaInfoEntity;
import com.tqjc.system.system.entity.SysMaterialInfoEntity;
import com.tqjc.system.system.model.vo.TaskMaterialEditVO;
import com.tqjc.system.system.model.vo.TaskMaterialOptVO;
import com.tqjc.system.system.service.SysAddDetailTaskService;
import com.tqjc.system.system.service.SysAddPrimaryTaskService;
import com.tqjc.system.system.service.SysBusinessTaskService;
import com.tqjc.system.system.service.SysMaterialManageService;
import com.tqjc.system.system.wrapper.AddDetailTaskWrapper;
import com.tqjc.system.system.wrapper.AddPrimaryTaskWraper;
import com.tqjc.system.system.wrapper.AddTaskVOWrapper;
import com.tqjc.system.system.wrapper.AreaManageWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 加料任务控制层
 * @Author: 86195
 * @Date: 2023/12/14 11:20
 **/
@Controller
@Slf4j
@RequestMapping("/sys/addTask")
public class SysAddTaskController extends BaseController {

    @Autowired
    private SysAddDetailTaskService detailTaskService;

    @Autowired
    private SysMaterialManageService materialService;

    @Autowired
    private SysBusinessTaskService sysBusinessTaskService;

    @Autowired
    private SysAddPrimaryTaskService primaryTaskService;

    @RequestMapping("/taskDistribute/index")
    public String taskDistribute(){

        return "sys/addTask/taskDistribute.html";
    }



    @RequestMapping("/taskExecute/index")
    public String taskExecute(){

        return "sys/addTask/taskeExecution.html";
    }


    @RequestMapping("/taskExecute/MESTask")
    public String MESTask(){

        return "sys/addTask/MESTaskDistribute.html";
    }



    @RequestMapping("/taskQuery/index")
    public String taskQueryIndex(){

        return "sys/addTask/taskQueryIndex.html";
    }


    @RequestMapping("/infoList")
    public void taskQueryInfoList(TaskInfoVO taskInfoVO, PageInfo<SysAddPrimaryTaskEntity> page, HttpServletResponse response){
        log.info("查询历史任务信息接口开始");
        initDate(taskInfoVO);
        IPage<SysAddPrimaryTaskEntity> lstResult = primaryTaskService.selectListByPage(page.getPageEntity(),taskInfoVO);
        ResponseUtil.write(response, new AddPrimaryTaskWraper(lstResult).wrap());
        log.info("查询历史任务信息接口结束");
    }


    @RequestMapping("/queryTaskDetail")
    public void queryTaskDetailByTaskID(String taskId, PageInfo<SysAddDetailTaskEntity> page, HttpServletResponse response){
        log.info("查询历史详情子任务信息接口开始");
        List<SysAddDetailTaskEntity> lstResult = detailTaskService.getDetailTaskInfo(taskId);
        ResponseUtil.write(response, new AddDetailTaskWrapper(lstResult).wrap());
        log.info("查询历史详情子任务信息接口结束");
    }


    @RequestMapping("/getTaskInfo")
    @ResponseBody
    public AjaxJson getTaskInfo(String taskId){
        log.info("MES下发查询任务接口开始");
        AjaxJson ajaxJson = new AjaxJson();
        try {

            List<SysAddDetailTaskEntity> lstResult = detailTaskService.getDetailTaskInfo(taskId);
            ajaxJson.setObj(lstResult);
        } catch (Exception e){
            log.info("MES下发查询任务接口出现异常",e);
            ajaxJson.setSuccess(false);
        }

        log.info("MES下发查询任务接口结束");
        return ajaxJson;
    }


    @RequestMapping("/initTaskExecution")
    public void initTaskExecution(String tankCarNo,  HttpServletResponse response){
        try {
            log.info("查询槽车任务接口开始");
            List<SysAddDetailTaskEntity> resList = detailTaskService.getDetailTaskInfoByTankCarNo(tankCarNo);
            AddDetailTaskWrapper addDetailTaskWrapper = new AddDetailTaskWrapper(resList);
            ResponseUtil.write(response, addDetailTaskWrapper.wrap());
            log.info("查询槽车任务接口结束");

        } catch (Exception e){
            log.error("获取对应槽车任务详情信息异常",e);
        }
    }


    @RequestMapping("/initPrimaryTaskExecution")
    public void initPrimaryTaskExecution(String tankCarNo,  HttpServletResponse response){
        try {
            log.info("查询槽车任务接口开始");
            List<AddTaskVO> resList = detailTaskService.getPrimaryTaskInfoByTankCarNo(tankCarNo);
            ResponseUtil.write(response, new AddTaskVOWrapper(resList).wrap());
            log.info("查询槽车任务接口结束");

        } catch (Exception e){
            log.error("获取对应槽车任务详情信息异常",e);
        }
    }


    @RequestMapping("/addOpt")
    @ResponseBody
    public AjaxJson addOpt(String tankCarNo){
        AjaxJson ajaxJson = new AjaxJson();
        try {
            log.info("新增主任务接口开始");
            primaryTaskService.addOpt(tankCarNo);
            ajaxJson.setMsg("新增主任务成功");
            log.info("新增主任务接口结束");

        } catch (Exception e){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("新增主任务失败");
            log.error("获取对应槽车任务详情信息异常",e);
        }
        return ajaxJson;
    }




    private void initDate(TaskInfoVO taskInfoVO) {
        if(StringUtils.isNotEmpty(taskInfoVO.getComStartDateStr())){
            String startDateStr = taskInfoVO.getComStartDateStr() + " 00:00:00";
            taskInfoVO.setComStartDate(DateUtils.getLocalDateTime(startDateStr));
        }

        if(StringUtils.isNotEmpty(taskInfoVO.getComEndDateStr())){
            String endDate = taskInfoVO.getComEndDateStr() + " 23:59:59";
            taskInfoVO.setComEndDate(DateUtils.getLocalDateTime(endDate));
        }

        if(StringUtils.isNotEmpty(taskInfoVO.getDistStartDateStr())){
            String startDateStr = taskInfoVO.getDistStartDateStr() + " 00:00:00";
            taskInfoVO.setDistStartDate(DateUtils.getLocalDateTime(startDateStr));
        }

        if(StringUtils.isNotEmpty(taskInfoVO.getDistEndDateStr())){
            String endDate = taskInfoVO.getDistEndDateStr() + " 23:59:59";
            taskInfoVO.setDistEndDate(DateUtils.getLocalDateTime(endDate));
        }

    }


    @RequestMapping("/taskDistribute/getDetailTaskInfo")
    @ResponseBody
    public AjaxJson getDetailTaskInfo(String tankCarNo){
        AjaxJson ajaxJson = new AjaxJson();
        log.info("获取对应槽车任务详情信息开始,槽车号：{}",tankCarNo);

        try {

            List<SysAddDetailTaskEntity> resList = detailTaskService.getDetailTaskInfoByTankCarNo(tankCarNo);
            AddDetailTaskWrapper addDetailTaskWrapper = new AddDetailTaskWrapper(resList);
            ajaxJson.setObj(addDetailTaskWrapper);
            log.info("获取对应槽车任务详情信息结束,槽车号：{}",tankCarNo);

        } catch (Exception e){
            log.error("获取对应槽车任务详情信息异常",e);
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("请求异常，请联系管理员！！");
        }
        return ajaxJson;
    }


    @RequestMapping("/openPage")
    public String toAddPage(String  taskId,String idKey,String oprType,String tankCarNo, Model model){
        model.addAttribute("taskId",taskId);
        model.addAttribute("idKey",idKey);
        model.addAttribute("oprType",oprType);
        model.addAttribute("tankCarNo",tankCarNo);
        return "sys/addTask/materialDetail.html";
    }


    @RequestMapping("/taskDetailIndex")
    public String toTaskDetail(String  taskId, Model model){
        model.addAttribute("taskId",taskId);
        return "sys/addTask/taskDetail.html";
    }


    @RequestMapping("/openEditPage")
    public String toEditPage(String idKey,Model model){
        SysAddDetailTaskEntity taskEntity = detailTaskService.getById(idKey);
        taskEntity.setStatusDesc(TaskStatusEnum.getDescByStatus(taskEntity.getStatus()));
        model.addAttribute("taskEntity",taskEntity);
        return "sys/addTask/editMaterial.html";
    }


    @RequestMapping("/initMaterialInfo")
    @ResponseBody
    public AjaxJson initMaterialInfo(){
        AjaxJson ajaxJson = new AjaxJson();
        List<SysMaterialInfoEntity> list = materialService.getAllListByStatus(GlobalConstant.STATUS_1);
        ajaxJson.setObj(list);
        return ajaxJson;
    }


    @RequestMapping("/saveMaterialOpt")
    @ResponseBody
    public AjaxJson saveMaterialOpt(TaskMaterialOptVO materialOptVO){
        String taskId = materialOptVO.getTaskId();
        String oprType = materialOptVO.getOprType();
        log.info("任务id：{}开始对物料进行操作,操作类型为：{}",taskId,oprType);
        AjaxJson ajaxJson = new AjaxJson();

        try {
            TaskTypeEnum taskTypeEnum = TaskTypeEnum.getEnumByType(oprType);
            taskTypeEnum.saveOpt(sysBusinessTaskService,materialOptVO);
            ajaxJson.setMsg(taskTypeEnum.getSuccessMsg());
        } catch (Exception e){
            log.error("任务id：{}开始对物料进行操作,操作类型为：{}。出现异常",taskId,oprType,e);
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("新增失败,请联系管理员");
        }

        log.info("任务id：{}完成对物料进行操作,操作类型为：{}",taskId,oprType);
        return ajaxJson;
    }


    @RequestMapping("/confirm")
    @ResponseBody
    public AjaxJson optFinish(TaskMaterialOptVO taskMaterialOptVO){
        AjaxJson ajaxJson = new AjaxJson();
        try {
            log.info("任务下发接口开始");


            if(AddTaskConstant.CAR_STATUS_FLAG){
                boolean flag = sysBusinessTaskService.checkCarStatus(taskMaterialOptVO.getSpanNo());
                if(!flag){
                    log.info("任务下发接口失败，天车状态未处于自动状态");
                    ajaxJson.setMsg("下发失败，天车状态未处于自动状态");
                    ajaxJson.setSuccess(false);
                    return ajaxJson;
                }
            }

            sysBusinessTaskService.frontConfirm(taskMaterialOptVO);
            log.info("任务下发接口结束");
            ajaxJson.setMsg("操作成功");

        } catch (Exception e){
            log.error("任务下发接口出现异常",e);
            ajaxJson.setMsg("操作失败");

        }

        return ajaxJson;
    }


    @RequestMapping("/confirmForMES")
    @ResponseBody
    public AjaxJson confirmForMES(TaskMaterialOptVO taskMaterialOptVO){
        AjaxJson ajaxJson = new AjaxJson();
        try {
            log.info("MES任务下发接口开始");
            if(AddTaskConstant.CAR_STATUS_FLAG){
                boolean flag = sysBusinessTaskService.checkCarStatus(taskMaterialOptVO.getSpanNo());
                if(!flag){
                    log.info("MES任务下发接口失败，天车状态未处于自动状态");
                    ajaxJson.setMsg("下发失败，天车状态未处于自动状态");
                    ajaxJson.setSuccess(false);
                    return ajaxJson;
                }
            }


            sysBusinessTaskService.confirmForMES(taskMaterialOptVO);
            log.info("MES任务下发接口结束");
            ajaxJson.setMsg("操作成功");

        } catch (Exception e){
            log.error("MES任务下发接口出现异常",e);
            ajaxJson.setMsg("操作失败");

        }

        return ajaxJson;
    }

    @RequestMapping("/checkCarStatus")
    @ResponseBody
    public AjaxJson checkCarStatus(String spanNo){
        //下发前检查天车点位状态是否已准备好
        AjaxJson ajaxJson = new AjaxJson();
        log.info("检查天车状态接口开始！！");
        if(AddTaskConstant.CAR_STATUS_FLAG){
            boolean flag = sysBusinessTaskService.checkCarStatus(spanNo);
            if(!flag){
                log.info("检查天车状态接口，天车状态未准备好！！！！");
                ajaxJson.setMsg("操作失败，天车未处于自动化状态");
                ajaxJson.setSuccess(false);
                return ajaxJson;
            }
        }
        log.info("检查天车状态接口结束！！");
        ajaxJson.setMsg("校验成功！！");
        return ajaxJson;
    }


    @RequestMapping("/del")
    @ResponseBody
    public AjaxJson delete(TaskMaterialOptVO taskMaterialOptVO){
        AjaxJson ajaxJson = new AjaxJson();
        try {
            log.info("子任务删除接口开始");

            sysBusinessTaskService.frontDel(taskMaterialOptVO);
            log.info("子任务删除接口结束");
            ajaxJson.setMsg("操作成功");

        } catch (Exception e){
            log.error("子任务删除接口出现异常",e);
            ajaxJson.setMsg("操作失败");

        }

        return ajaxJson;
    }


    @RequestMapping("/forceFinishTask")
    @ResponseBody
    public AjaxJson forceFinishTask(String taskId){
        AjaxJson ajaxJson = new AjaxJson();
        try {
            log.info("强制结束任务接口开始");

            sysBusinessTaskService.forceFinishTask(taskId);
            log.info("强制结束任务接口结束");
            ajaxJson.setMsg("操作成功");

        } catch (Exception e){
            log.error("强制结束任务接口出现异常",e);
            ajaxJson.setMsg("操作失败");

        }

        return ajaxJson;
    }


    @RequestMapping("/fixAbnormal")
    @ResponseBody
    public AjaxJson fixAbnormal(String carName){
        AjaxJson ajaxJson = new AjaxJson();

        try {
            log.info("修复异常接口开始,天车名称：{}",carName);

            //todo 修复异常接口
            sysBusinessTaskService.fixAbnormal(carName);
            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("操作成功");
            log.info("修复异常接口结束,天车名称：{}",carName);
        } catch (Exception e){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("操作失败");
            log.error("修复异常接口出现异常,天车名称：{}",carName,e);

        }
        return ajaxJson;

    }


    @RequestMapping("/resumeTask")
    @ResponseBody
    public AjaxJson resumeTask(String carName){
        AjaxJson ajaxJson = new AjaxJson();

        try {
            log.info("继续执行任务接口开始,天车名称为：{}",carName);

            sysBusinessTaskService.resumeTask(carName);
            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("操作成功");
            log.info("继续执行任务接口结束,天车名称为：{}",carName);

        } catch (Exception e){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("操作失败");

            log.error("继续执行任务接口出现异常,天车名称为：{}",carName,e);

        }

        return ajaxJson;

    }


    @RequestMapping("/refresh")
    @ResponseBody
    public AjaxJson refresh(String taskId){
        AjaxJson ajaxJson = new AjaxJson();

        try {
            log.info("继续执行任务接口开始,taskId为：{}",taskId);
            if(GlobalConstant.VISIT_MODEL_FLAG){
                ajaxJson.setSuccess(true);
                ajaxJson.setMsg("操作成功");
                sysBusinessTaskService.refresh(taskId);
                return ajaxJson;
            }

            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("参观开关没打开，不能执行刷新任务");
            log.info("继续执行任务接口结束,taskId为：{}",taskId);

        } catch (Exception e){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("操作失败");

            log.error("继续执行任务接口出现异常,taskId为：{}",taskId,e);

        }


        return ajaxJson;

    }










}
